package com.kuhyygy.xml;

import java.util.ArrayList;
import java.util.List;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

import android.util.Log;

import com.kuhyygy.bean.Person;

public class BaseXmlHandler extends DefaultHandler {

	private String tag = "BaseXmlHandler";
	
	private List<Person> persons;
	private Person person;
	private String preTag;
	

	@Override
	public void characters(char[] ch, int start, int length)
			throws SAXException {
		String data = new String(ch, start, length);
		if (null != person) {
			if ("name".equals(preTag)) {
				person.setName(data);
			} else if ("age".equals(preTag)) {
				person.setAge((short)Short.parseShort(data));
			}
		}
		Log.i(tag, "--->" + preTag + " 解释内容:" + data);
	}

	@Override
	public void endDocument() throws SAXException {
		super.endDocument();
		Log.i(tag , "文件解释完毕");
	}

	@Override
	public void startDocument() throws SAXException {
		Log.i(tag , "开始解释文件");
		persons = new ArrayList<Person>();
	}

	@Override
	public void startElement(String uri, String localName, String qName,
			Attributes attrs) throws SAXException {
		if ("person".equals(localName)) {
			person = new Person();
			person.setId(attrs.getValue("id"));
		}
		preTag = localName;
		Log.i(tag, "#### " + preTag);
	}

	@Override
	public void endElement(String uri, String localName, String qName)
			throws SAXException {
		if ("person".equals(localName) && null != person) {
			persons.add(person);
			person = null;
		}
		preTag = null;
	}
	
	public List<Person> getPersons() {
		return persons;
	}

}
